package com.yhw.srb.oss.controller.api;

import com.yhw.common.exception.BusinessException;
import com.yhw.common.result.R;
import com.yhw.common.result.ResponseEnum;
import com.yhw.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/api/oss/file")
//@CrossOrigin
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "目录",required = true)
            @RequestParam("module")String module) {

        try {
            InputStream inputStream = file.getInputStream();
            // 原始文件名称  比如 aa.png
            String filename = file.getOriginalFilename();
            String uploadurl = fileService.upload(inputStream, module, filename);

            // 上传成功 要把文件的 url 返回给前端
            return R.ok().message("文件上传成功").data("url",uploadurl);
        } catch (IOException e) {
            // UPLOAD_ERROR(-103, "文件上传错误"),
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("删除oss文件")
    @DeleteMapping("/remove")
    public R remove(@ApiParam(value = "要删除文件的路径",required = true) @RequestParam("url") String url){
        fileService.remove(url);
        return R.ok().message("删除成功");
    }



}
